//
//  HTOAuthViewController.swift
//  weibo
//
//  Created by JonsonLiu on 2017/2/27.
//  Copyright © 2017年 JonsonLiu. All rights reserved.
//

import UIKit
import SVProgressHUD


class HTOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=1517425051&redirect_uri=https://www.baidu.com/"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(url: url! as URL)
        webView.loadRequest(request as URLRequest)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    private func setupUI(){
    
        self.view.backgroundColor = UIColor.white
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(Stream.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: "autoFill")
        
    }
    
    
     func close(){
        self.dismiss(animated: true, completion: nil)
    }
    
     func autoFill(){
    
        let urlString = "document.getElementById('userId').value = 'ljskd2@163.com';document.getElementById('passwd').value = 'ljs5211'"
        
        webView.stringByEvaluatingJavaScript(from: urlString)
        
    }
    
    
    private lazy var webView : UIWebView = {
        
        let webView = UIWebView()
        webView.delegate = self
        return webView
    
    }()
    
    
}


extension HTOAuthViewController : UIWebViewDelegate {
    
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("res  = \(request)" )
        //比较一个URLRequest 是否包含前缀
        let url = request.url?.absoluteString.hasPrefix("https://www.baidu.com/")
        if url == true {
            
             let q = request.url?.query
            //判断是否包含字符串
            if  (q?.contains("code="))! {
                //截取字符串
                let code = q!.substring(from: "code=".endIndex)
                
                print(code)
                
                loadAccessToken(code: code)
                
                           }
        
        }
        
        
        
            return true
    }
    
    func loadAccessToken(code : String){
        
        let params = [
            "client_id": "1517425051",
            "client_secret": "9c4b83040b807792dfa115f8930dbf14",
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "https://www.baidu.com/"
        ]
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        NetworkTools.shardTools.request(method: .Post, urlString: urlString, parameters: params as AnyObject?) { (responseObject, error) in
            
            if error != nil {
                print(error!)
                return
            }
            
            guard (responseObject as? [String : AnyObject]) != nil else{
            
                return
            }
            
             guard let dict = responseObject as? [String : AnyObject] else {
                print("chucuo ")
                return
            }
            
//            print(responseObject!)
            let acctount = HTAccountModel(dict : dict)
            print("111111  \(acctount.access_token)")
            
            //获取用户接口
            self.loadUserInformation(acctount: acctount)
        }

    
    }
    
    func loadUserInformation(acctount : HTAccountModel ){
    
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token" : acctount.access_token,
            "uid" : acctount.uid
        ]
        NetworkTools.shardTools.request(method: .Get, urlString: urlString, parameters: param as AnyObject?) { (responseObject, error) in
            print(responseObject)
        }
        
    }
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
